﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections;
using GPCSC.Web;
using NickLee.Web.UI;
using NickLee.Common;
namespace GPCSC.Web.SYS_ORG
{
    public partial class PostEdit : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.f_SelectDataBind();
                this.command.Value = Usual.f_querystringToString("command");
                if (this.command.Value == "View")
                {
                    string postid = Usual.f_querystringToString("CommandArg");
                    f_fristLoad(postid);
                    UIFactory.UIFactory_ReadOnly(this);
                    this.buttontr.Style.Add("display","none");
                }
                else if (this.command.Value == "Edit")
                {
                    string postid = Usual.f_querystringToString("CommandArg");
                    UIFactory.UIFactory_NotReadOnly(this);
                    f_fristLoad(postid);
                }
                this.MtxtD_CL_PARPOSTID_PK.Text = "";
            }
        }

        protected void f_fristLoad(string PrimaryKey)
        { 
            base.o_uiTable.Clear();
            SqlReadXml org = new SqlReadXml();
            base.o_uiTable.Add("@POSTID", PrimaryKey);
            base.m_uiDataSet = org.ReaderDataSet("sel_post_one", base.o_uiTable);
            if (base.m_uiDataSet.Tables.Count > 0)
            {
                if (base.m_uiDataSet.Tables[0].Rows.Count > 0)
                {
                    //UIFactory set UI controls value:界面工厂设置界面控件值
                    try
                    {
                        base.o_uiTable = UIFactory.UIFactory_Set(this, base.m_uiDataSet.Tables[0]);

                    }
                    catch
                    {

                    }
                    //your can do databind yourself:对界面工厂不能填充的数据，通过ODRM手动填充
                    GPCSC.Model.CL_POST_S objModel = new GPCSC.Model.CL_POST_S();
                    var row = base.m_uiDataSet.Tables[0].Rows[0];
                    ODRM.DataRowConvertObject(row, objModel);
                    this.ComboBox1.Text = Usual.f_convertString(row["PARPOSTNAME"]);

                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            savepost();
        }
        protected void savepost()
        {
            int number = 0;
            try
            {
                if (this.command.Value == "new")
                {

                    SqlReadXml org = new SqlReadXml();
                    Hashtable ht = new Hashtable();
                    DataSet dss = org.ReaderDataSet("sel_PostmaxNumber", ht);
                    string aa = dss.Tables[0].Rows[0]["maxNumber"].ToString().Trim();
                    if (aa != "" && aa != null)
                    {
                        number = Convert.ToInt32(aa);
                    }
                    else
                    {
                        number = 0;
                    }

                    Guid POSTID = Guid.NewGuid();
                    Hashtable postTable = new Hashtable();
                    postTable.Add("@POSTID", POSTID);
                    postTable.Add("@POSTNAME", this.MtxtD_POSTNAME.Value.ToString());
                    postTable.Add("@REMARK", this.MtxtD_REMARK.Text.ToString());
                    postTable.Add("@Number", number + 1);
                    postTable.Add("@status", 0);//先默认为0可用
                    if (this.MtxtD_CL_PARPOSTID_PK.Text.Trim() != "")
                    {
                        string[] data = this.MtxtD_CL_PARPOSTID_PK.Text.Trim().Split('&');
                        postTable.Add("@PARPOSTID", new Guid(data[0]));
                        postTable.Add("@PARPOSTNAME", this.MtxtD_PARPOSTNAME.Text.ToString());
                        postTable.Add("@DEPTH", Convert.ToInt32(data[1]) + 1);

                    }
                    else
                    {
                        postTable.Add("@PARPOSTID", new Guid("00000000-0000-0000-0000-000000000000"));
                        postTable.Add("@PARPOSTNAME", "");
                        postTable.Add("@DEPTH", 0);
                    }
                    SqlReadXml Org = new SqlReadXml();
                    DataSet ds = new DataSet();
                    ds = Org.ReaderDataSet("sel_postname_one", postTable);
                    if (ds.Tables[0].Rows.Count == 0)
                    {
                        Org.NotDoSQL("ins_post_one", postTable);

                       
                        this.Response.Write("<script>alert('添加单位成功！');window.location.href='PostList.aspx';</script>");
                    }
                    else
                    {
                        this.Response.Write("<script>alert('添加单位失败 存在相同名称的单位！');</script>");

                    }
                }

                else
                {

                    SqlReadXml org = new SqlReadXml();
                    base.o_uiTable = this.f_getElements(base.o_uiTable);
                    string perid = "";
                    int depth = -1;
                    if (this.MtxtD_CL_PARPOSTID_PK.Text.Trim() != "")
                    {
                        string[] data = this.MtxtD_CL_PARPOSTID_PK.Text.Trim().Split('&');
                        if (data[0].ToString() == Usual.f_convertString(base.o_uiTable["POSTID"]))
                        {
                           
                            this.Response.Write("<script>alert('父部门不能为本身,请重新选择！');</script>");
                            return;
                        }
                        perid = data[0].ToString();
                        try
                        {
                            depth = Usual.f_convertInt32(data[1].ToString());
                        }
                        catch (Exception ex)
                        {
                        }
                    }


                    //先查找有无子部门
                    string deptname = "";
                    DataSet dset = new DataSet();
                    dset = org.ReaderDataSet("sel_postchild_info", base.o_uiTable);
                    if (dset.Tables[0].Rows.Count > 0)
                    {
                      
                        deptname = deptname + dset.Tables[0].Rows[0]["PARPOSTNAME"].ToString() + ",";

                    }

              
                    SqlReadXml Org = new SqlReadXml();
                    Model.CL_POST_S post = new GPCSC.Model.CL_POST_S();
                    BLL.CL_POST_S postbll = new GPCSC.BLL.CL_POST_S();

                    post = postbll.GetModel(Usual.f_convertGuid(Usual.f_querystringToString("CommandArg")));
                    post.POSTNAME = MtxtD_POSTNAME.Value.ToString();
                    post.REMARK = MtxtD_REMARK.Text.ToString();
                    //post.isMain = Usual.f_convertInt32(MtxtD_isMain.SelectedValue.ToString());
                    post.PARPOSTNAME = MtxtD_PARPOSTNAME.Text.ToString();
                    post.Depth = depth + 1;

                        post.CL_PARPOSTID_PK = Usual.f_convertGuid(perid);
               
                    postbll.Update(post);



                    this.Response.Write("<script>alert('更新数据成功!');window.location.href='PostList.aspx';</script>");
               
                }
            }
            catch (Exception ewe)
            {
                throw ewe;
            }
        }

        /// <summary>
        /// UIFactory Get Values:通过UIFactory界面工厂获取值
        /// </summary>
        /// <param name="o_uiTable">Filled Hashtable:返回填充后的哈希表</param>
        public Hashtable f_getElements(Hashtable o_uiTable)
        {
            //UIFactory Get Values as Hashtable:界面工厂获取值，并保存在哈希表
            base.o_uiTable.Clear();
            base.o_uiTable = UIFactory.UIFactory_Get(this);
            if (Usual.f_querystringToObj("CommandArg") != null)
            {
                base.o_uiTable.Add("POSTID", Usual.f_convertString(Usual.f_querystringToObj("CommandArg")));
            }
            return base.o_uiTable;
        }


        private void f_SelectDataBind()
        {
            if (!IsPostBack)
            {
                #region TreeView绑定部门
                try
                {
                    DataSet set1 = new DataSet();
                    SqlReadXml Org = new SqlReadXml();
                    set1 = Org.ReaderDataSet("sel_POST_all");
                    this.buildTree(TreeView1, set1);

                }
                catch (System.Exception ee)
                {
                    // base.m_loger.Error("缓存失效或者Session控制错误!", ee);
                    return;
                }
                #endregion
            }
        }
        #region TreeView结构无限级填充



        protected bool buildTree(NickLee.Web.UI.TreeView TreeViewName, DataSet ds)
        {
            //清空所有节点
            TreeViewName.Nodes.Clear();
            //如果为最高级，则修改以适应ds的relation中的关系
            foreach (DataRow dbRow in ds.Tables[0].Rows)
            {
                if (Usual.f_convertString(dbRow["CL_PARPOSTID_PK"]) == "00000000-0000-0000-0000-000000000000")
                    //if (dbRow["PARMENUID"].ToString() == "0")
                    //{
                    dbRow["CL_PARPOSTID_PK"] = DBNull.Value;
                //}
            }
            //设置ds中父子级relation
            try
            {
                if (ds.Relations["NodeRelation"] == null)
                {
                    ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["CL_POST_SOID"], ds.Tables[0].Columns["CL_PARPOSTID_PK"]);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            //循环绑定父node
            foreach (DataRow dbRow in ds.Tables[0].Rows)
            {
                if (dbRow.IsNull("CL_PARPOSTID_PK"))
                {
                    TreeViewNode newNode =
                        CreateTreeNode(dbRow["POSTNAME"].ToString(), dbRow["CL_POST_SOID"].ToString() + "&" + dbRow["DEPTH"].ToString());
                    if (newNode != null)
                    {
                        TreeViewName.Nodes.Add(newNode);
                    }
                    PopulateSubTree(dbRow, newNode);
                }
            }
            return true;
        }

        /// <summary>
        /// 循环绑定子node
        /// </summary>
        /// <param name="dbRow">dataset的行</param>
        /// <param name="node">需要添加的节点</param>
        private void PopulateSubTree(DataRow dbRow, TreeViewNode node)
        {
            foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
            {
                TreeViewNode childNode = CreateTreeNode(childRow["POSTNAME"].ToString(), childRow["CL_POST_SOID"].ToString() + "&" + childRow["DEPTH"].ToString());
                if (childNode != null)
                {
                    node.Nodes.Add(childNode);
                }
                PopulateSubTree(childRow, childNode);
            }
        }


        /// <summary>
        /// 给所有node附加属性
        /// </summary>
        /// <param name="text">呈现文本</param>
        /// <returns>返回node</returns>
        private TreeViewNode CreateTreeNode(string text, string id)
        {
            TreeViewNode node = new TreeViewNode();
            node.Text = text;
            node.ID = id;
            node.Expanded = true;
            // node.ContentCallbackUrl = "./N_SEC_USER_ListTreeViewXml.aspx?ParentNodeId=" + id.ToString();
            return node;
        }
        #endregion
    }
}